package org.budo.warehouse.logic.impl;

import java.util.HashMap;
import java.util.Map;

import org.budo.support.java.regex.util.RegexUtil;
import org.budo.support.lang.util.StringUtil;
import org.budo.support.spring.expression.util.SpelUtil;
import org.budo.warehouse.logic.api.DataEntry;
import org.budo.warehouse.logic.api.IEventFilterLogic;
import org.budo.warehouse.service.entity.Pipeline;
import org.springframework.stereotype.Service;

/**
 * @author lmw
 */
@Service
public class EventFilterLogicImpl implements IEventFilterLogic {
    @Override
    public boolean filter(Pipeline pipeline, DataEntry dataEntry) {
        return this.bySchema(pipeline, dataEntry) //
                && this.byTable(pipeline, dataEntry) //
                && this.byEventFilter(pipeline, dataEntry);
    }

    /**
     * 库名正则筛选
     */
    private boolean bySchema(Pipeline pipeline, DataEntry dataEntry) {
        String sourceSchema = pipeline.getSourceSchema();
        if (StringUtil.isEmpty(sourceSchema)) {
            return true;
        }

        return RegexUtil.matches(sourceSchema, dataEntry.getSchemaName());
    }

    /**
     * 表名正则筛选
     */
    private boolean byTable(Pipeline pipeline, DataEntry dataEntry) {
        String sourceTable = pipeline.getSourceTable();
        if (StringUtil.isEmpty(sourceTable)) {
            return true;
        }

        return RegexUtil.matches(sourceTable, dataEntry.getTableName());
    }

    /**
     * 类型等,SPEL筛选
     */
    private boolean byEventFilter(Pipeline pipeline, DataEntry dataEntry) {
        String eventFilter = pipeline.getEventFilter();
        if (StringUtil.isEmpty(eventFilter)) {
            return true;
        }

        if (!eventFilter.startsWith("#{")) {
            throw new IllegalArgumentException("#25 eventFilter=" + eventFilter + ", pipeline=" + pipeline);
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("eventType", dataEntry.getEventType());
        map.put("schemaName", dataEntry.getSchemaName());
        map.put("tableName", dataEntry.getTableName());

        String merge = SpelUtil.merge(eventFilter, map);
        return "true".equals(merge);
    }
}